
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import WorkflowStepTask, WorkflowInstance, WorkflowTemplate, Asset
from django.contrib.auth.models import User
from .forms_workflow import AssetBorrowRequestForm

@login_required
def task_list(request):
    """显示分配给当前用户的待处理工作流任务"""
    from django.core.paginator import Paginator

    # 获取筛选参数
    status_filter = request.GET.get('status')
    type_filter = request.GET.get('type')

    # 待处理任务
    pending_tasks = WorkflowStepTask.objects.filter(
        assignee=request.user,
        status='pending'
    ).select_related('workflow_instance', 'workflow_instance__created_by').order_by('created_at')

    # 已处理任务
    processed_tasks_query = WorkflowStepTask.objects.filter(
        assignee=request.user
    ).exclude(status='pending').select_related('workflow_instance').order_by('-completed_at')

    if status_filter:
        processed_tasks_query = processed_tasks_query.filter(status=status_filter)
    
    if type_filter:
        processed_tasks_query = processed_tasks_query.filter(workflow_instance__template__template_type=type_filter)

    # 分页
    paginator = Paginator(processed_tasks_query, 10)  # 每页10条
    page_number = request.GET.get('page')
    processed_tasks_page = paginator.get_page(page_number)

    context = {
        'pending_tasks': pending_tasks,
        'processed_tasks': processed_tasks_page,
        'status_choices': WorkflowStepTask.TASK_STATUS_CHOICES,
        'type_choices': WorkflowTemplate.TEMPLATE_TYPE_CHOICES,
        'selected_status': status_filter,
        'selected_type': type_filter,
    }
    return render(request, 'assets/workflow_task_list.html', context)

@login_required
def process_task(request, task_id):
    """处理一个工作流任务（批准或拒绝）"""
    task = get_object_or_404(WorkflowStepTask, id=task_id, assignee=request.user)

    if task.status != 'pending':
        messages.error(request, "这个任务已被处理或取消。")
        return redirect('assets:task_list')

    if request.method == 'POST':
        action = request.POST.get('action')
        comments = request.POST.get('comments', '')

        try:
            if action == 'approve':
                task.complete(comments=comments)
                execute_workflow_actions(task, 'on_approve')
                messages.success(request, f"任务 ‘{task.step_name}’ 已批准。")
            elif action == 'reject':
                task.reject(comments=comments)
                execute_workflow_actions(task, 'on_reject')
                messages.warning(request, f"任务 ‘{task.step_name}’ 已拒绝。")
            else:
                messages.error(request, "无效的操作。")
        except Exception as e:
            messages.error(request, f"处理任务时出错: {e}")

        return redirect('assets:task_list')

    return redirect('assets:task_list')

def execute_workflow_actions(task, action_type):
    """执行工作流动作"""
    workflow_definition = task.workflow_instance.template.workflow_definition
    actions = workflow_definition.get('completion_actions', {}).get(action_type, {})

    if not actions:
        return

    if task.workflow_instance.related_object_type == 'asset':
        try:
            asset = Asset.objects.get(id=task.workflow_instance.related_object_id)
            if 'set_status' in actions:
                asset.status = actions['set_status']
            if 'set_user' in actions:
                if actions['set_user'] == '{{applicant}}':
                    asset.user = task.workflow_instance.created_by
                else:
                    asset.user = None # Or look up a specific user
            asset.save()
        except Asset.DoesNotExist:
            pass # Handle error

@login_required
def asset_borrow_request_create(request):
    """处理资产借用申请的表单和视图"""
    try:
        workflow_template = WorkflowTemplate.objects.get(template_type='asset_borrow', is_active=True)
    except WorkflowTemplate.DoesNotExist:
        messages.error(request, "“资产借用”工作流模板未找到或未启用。请联系管理员。")
        return redirect('assets:index')

    if request.method == 'POST':
        form = AssetBorrowRequestForm(request.POST)
        if form.is_valid():
            asset = form.cleaned_data['asset']
            reason = form.cleaned_data['reason']

            manager = User.objects.filter(is_superuser=True).first()
            if not manager:
                messages.error(request, "未找到审批人。请联系管理员设置。")
                return render(request, 'assets/asset_borrow_request_form.html', {'form': form})

            instance = WorkflowInstance.objects.create(
                template=workflow_template,
                instance_name=f"借用申请: {asset.name} (申请人: {request.user.username})",
                related_object_type='asset',
                related_object_id=asset.id,
                created_by=request.user,
                workflow_data={
                    'asset_id': asset.id,
                    'asset_name': asset.name,
                    'reason': reason,
                    'applicant_id': request.user.id,
                    'applicant_name': request.user.username
                }
            )

            try:
                instance.start()
                task = instance.step_tasks.first()
                if task:
                    task.assign_to(manager)
                
                messages.success(request, "您的资产借用申请已提交，正在等待审批。")
                return redirect('assets:asset_list')
            except Exception as e:
                messages.error(request, f"启动工作流失败: {e}")
                instance.delete()
                return render(request, 'assets/asset_borrow_request_form.html', {'form': form})
    else:
        form = AssetBorrowRequestForm()

    return render(request, 'assets/asset_borrow_request_form.html', {'form': form})


@login_required
def workflow_template_list(request):
    """工作流模板列表视图"""
    templates = WorkflowTemplate.objects.all()
    return render(request, 'assets/workflow_template_list.html', {'templates': templates})


@login_required
def workflow_template_create(request):
    """创建工作流模板视图"""
    if request.method == 'POST':
        form = WorkflowTemplateForm(request.POST)
        if form.is_valid():
            template = form.save(commit=False)
            template.created_by = request.user
            template.save()
            messages.success(request, '工作流模板创建成功。')
            return redirect('assets:workflow_template_list')
    else:
        form = WorkflowTemplateForm()
    return render(request, 'assets/workflow_template_form.html', {'form': form})


@login_required
def workflow_template_edit(request, pk):
    """编辑工作流模板视图"""
    template = get_object_or_404(WorkflowTemplate, pk=pk)
    if request.method == 'POST':
        form = WorkflowTemplateForm(request.POST, instance=template)
        if form.is_valid():
            form.save()
            messages.success(request, '工作流模板更新成功。')
            return redirect('assets:workflow_template_list')
    else:
        form = WorkflowTemplateForm(instance=template)
    return render(request, 'assets/workflow_template_form.html', {'form': form, 'template': template})


@login_required
def workflow_template_delete(request, pk):
    """删除工作流模板视图"""
    template = get_object_or_404(WorkflowTemplate, pk=pk)
    if request.method == 'POST':
        template.delete()
        messages.success(request, '工作流模板删除成功。')
        return redirect('assets:workflow_template_list')
    return render(request, 'assets/workflow_template_confirm_delete.html', {'template': template})


@login_required
def asset_scrap_request_create(request, asset_id):
    """处理资产报废申请的表单和视图"""
    asset = get_object_or_404(Asset, id=asset_id)
    try:
        workflow_template = WorkflowTemplate.objects.get(template_type='asset_scrap', is_active=True)
    except WorkflowTemplate.DoesNotExist:
        messages.error(request, "“资产报废”工作流模板未找到或未启用。请联系管理员。")
        return redirect('assets:asset_detail', pk=asset_id)

    if request.method == 'POST':
        form = AssetScrapRequestForm(request.POST)
        if form.is_valid():
            reason = form.cleaned_data['reason']

            manager = User.objects.filter(is_superuser=True).first()
            if not manager:
                messages.error(request, "未找到审批人。请联系管理员设置。")
                return render(request, 'assets/asset_scrap_request_form.html', {'form': form, 'asset': asset})

            instance = WorkflowInstance.objects.create(
                template=workflow_template,
                instance_name=f"报废申请: {asset.name} (申请人: {request.user.username})",
                related_object_type='asset',
                related_object_id=asset.id,
                created_by=request.user,
                workflow_data={
                    'asset_id': asset.id,
                    'asset_name': asset.name,
                    'reason': reason,
                    'applicant_id': request.user.id,
                    'applicant_name': request.user.username
                }
            )

            try:
                instance.start()
                task = instance.step_tasks.first()
                if task:
                    task.assign_to(manager)
                
                messages.success(request, "您的资产报废申请已提交，正在等待审批。")
                return redirect('assets:asset_detail', pk=asset_id)
            except Exception as e:
                messages.error(request, f"启动工作流失败: {e}")
                instance.delete()
                return render(request, 'assets/asset_scrap_request_form.html', {'form': form, 'asset': asset})
    else:
        form = AssetScrapRequestForm()

    return render(request, 'assets/asset_scrap_request_form.html', {'form': form, 'asset': asset})
